import {BrowserWindow} from 'electron';
import {windowManager} from "../core";
import {addHandler} from "./handlers.ts";
import { logger, LogCategory } from '../logger';

/**
 * 设置标签页相关的IPC处理程序
 */
export function setupTabIpcHandlers() {
  logger.info('TabHandler', LogCategory.IPC, '设置标签页IPC处理程序');

  // 窗口管理
  addHandler('create-window', (_, url) => {
    try {
      logger.debug('TabHandler', LogCategory.IPC, `收到创建窗口请求, URL: ${url || 'default'}`);
      return windowManager.createWindow(url || undefined);
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, '创建窗口失败', error);
      throw error;
    }
  });

  addHandler('get-window-count', () => {
    try {
      const count = windowManager.getWindowCount();
      logger.debug('TabHandler', LogCategory.IPC, `获取窗口数量: ${count}`);
      return count;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, '获取窗口数量失败', error);
      throw error;
    }
  });

  addHandler('get-current-window-id', (event) => {
    try {
      const win = BrowserWindow.fromWebContents(event.sender);
      const id = win ? win.id : null;
      logger.debug('TabHandler', LogCategory.IPC, `获取当前窗口ID: ${id}`);
      return id;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, '获取当前窗口ID失败', error);
      return null;
    }
  });

  // 窗口状态管理
  addHandler('save-window-state', (event) => {
    try {
      const win = BrowserWindow.fromWebContents(event.sender);
      if (win) {
        const state = windowManager.saveWindowState(win.id);
        logger.debug('TabHandler', LogCategory.IPC, `保存窗口状态, ID: ${win.id}`);
        return state;
      }
      logger.warn('TabHandler', LogCategory.IPC, '无法保存窗口状态: 窗口不存在');
      return null;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, '保存窗口状态失败', error);
      return null;
    }
  });

  // 标签页管理
  addHandler('create-tab', (_, {windowId, url}) => {
    try {
      const tabManager = windowManager.getTabManager(windowId);
      if (!tabManager) {
        logger.warn('TabHandler', LogCategory.IPC, `创建标签页失败: 窗口不存在, ID: ${windowId}`);
        return null;
      }

      const tabId = tabManager.createTab(url);
      logger.debug('TabHandler', LogCategory.IPC, `创建标签页, 窗口ID: ${windowId}, 标签页ID: ${tabId}, URL: ${url}`);
      return tabId;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, `创建标签页失败, 窗口ID: ${windowId}:`, error);
      throw error;
    }
  });

  addHandler('close-tab', (_, {windowId, index}) => {
    try {
      const tabManager = windowManager.getTabManager(windowId);
      if (tabManager) {
        logger.debug('TabHandler', LogCategory.IPC, `关闭标签页, 窗口ID: ${windowId}, 索引: ${index}`);
        tabManager.closeTab(index);
        return true;
      }
      logger.warn('TabHandler', LogCategory.IPC, `关闭标签页失败: 窗口不存在, ID: ${windowId}`);
      return false;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, `关闭标签页失败, 窗口ID: ${windowId}, 索引: ${index}:`, error);
      return false;
    }
  });

  addHandler('switch-tab', (_, {windowId, index}) => {
    try {
      const tabManager = windowManager.getTabManager(windowId);
      if (tabManager) {
        logger.debug('TabHandler', LogCategory.IPC, `切换标签页, 窗口ID: ${windowId}, 索引: ${index}`);
        tabManager.switchTab(index);
        return true;
      }
      logger.warn('TabHandler', LogCategory.IPC, `切换标签页失败: 窗口不存在, ID: ${windowId}`);
      return false;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, `切换标签页失败, 窗口ID: ${windowId}, 索引: ${index}:`, error);
      return false;
    }
  });

  addHandler('refresh-tab', (_, {windowId, index}) => {
    try {
      const tabManager = windowManager.getTabManager(windowId);
      if (tabManager && index !== undefined) {
        // 刷新指定标签页
        logger.debug('TabHandler', LogCategory.IPC, `刷新指定标签页, 窗口ID: ${windowId}, 索引: ${index}`);
        const tabInfo = tabManager.getTabInfo(index);
        if (tabInfo) {
          windowManager.getTabManager(windowId)?.navigateTo(index, tabInfo.url || '');
        }
        return true;
      } else if (tabManager) {
        // 刷新当前标签页
        logger.debug('TabHandler', LogCategory.IPC, `刷新当前标签页, 窗口ID: ${windowId}`);
        tabManager.refreshCurrentTab();
        return true;
      }
      logger.warn('TabHandler', LogCategory.IPC, `刷新标签页失败: 窗口不存在, ID: ${windowId}`);
      return false;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, `刷新标签页失败, 窗口ID: ${windowId}:`, error);
      return false;
    }
  });

  // 导航控制
  addHandler('navigate-to', (_, {windowId, index, url}) => {
    try {
      const tabManager = windowManager.getTabManager(windowId);
      if (tabManager) {
        logger.debug('TabHandler', LogCategory.IPC, `导航到URL, 窗口ID: ${windowId}, 索引: ${index}, URL: ${url}`);
        tabManager.navigateTo(index, url);
        return true;
      }
      logger.warn('TabHandler', LogCategory.IPC, `导航到URL失败: 窗口不存在, ID: ${windowId}`);
      return false;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, `导航到URL失败, 窗口ID: ${windowId}, 索引: ${index}:`, error);
      return false;
    }
  });

  addHandler('go-back', (_, {windowId, index}) => {
    try {
      const tabManager = windowManager.getTabManager(windowId);
      if (tabManager) {
        logger.debug('TabHandler', LogCategory.IPC, `回退导航, 窗口ID: ${windowId}, 索引: ${index}`);
        tabManager.goBack(index);
        return true;
      }
      logger.warn('TabHandler', LogCategory.IPC, `回退导航失败: 窗口不存在, ID: ${windowId}`);
      return false;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, `回退导航失败, 窗口ID: ${windowId}, 索引: ${index}:`, error);
      return false;
    }
  });

  addHandler('go-forward', (_, {windowId, index}) => {
    try {
      const tabManager = windowManager.getTabManager(windowId);
      if (tabManager) {
        logger.debug('TabHandler', LogCategory.IPC, `前进导航, 窗口ID: ${windowId}, 索引: ${index}`);
        tabManager.goForward(index);
        return true;
      }
      logger.warn('TabHandler', LogCategory.IPC, `前进导航失败: 窗口不存在, ID: ${windowId}`);
      return false;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, `前进导航失败, 窗口ID: ${windowId}, 索引: ${index}:`, error);
      return false;
    }
  });

  // 获取标签页信息
  addHandler('get-tab-info', (_, {windowId, index}) => {
    try {
      const tabManager = windowManager.getTabManager(windowId);
      if (tabManager) {
        const tabInfo = tabManager.getTabInfo(index);
        logger.debug('TabHandler', LogCategory.IPC, `获取标签页信息, 窗口ID: ${windowId}, 索引: ${index}`);
        return tabInfo;
      }
      logger.warn('TabHandler', LogCategory.IPC, `获取标签页信息失败: 窗口不存在, ID: ${windowId}`);
      return null;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, `获取标签页信息失败, 窗口ID: ${windowId}, 索引: ${index}:`, error);
      return null;
    }
  });

  // 获取所有标签页
  addHandler('get-all-tabs', (_, {windowId}) => {
    try {
      const tabManager = windowManager.getTabManager(windowId);
      if (!tabManager) {
        logger.warn('TabHandler', LogCategory.IPC, `获取所有标签页失败: 窗口不存在, ID: ${windowId}`);
        return [];
      }

      const tabs = [];
      let index = 0;
      let tabInfo = tabManager.getTabInfo(index);

      while (tabInfo) {
        tabs.push(tabInfo);
        index++;
        tabInfo = tabManager.getTabInfo(index);
      }

      logger.debug('TabHandler', LogCategory.IPC, `获取所有标签页, 窗口ID: ${windowId}, 数量: ${tabs.length}`);
      return tabs;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, `获取所有标签页失败, 窗口ID: ${windowId}:`, error);
      return [];
    }
  });

  // 添加休眠标签页处理程序
  addHandler('hibernate-tab', (_, {windowId, index}) => {
    try {
      const tabManager = windowManager.getTabManager(windowId);
      if (tabManager) {
        logger.debug('TabHandler', LogCategory.IPC, `休眠标签页, 窗口ID: ${windowId}, 索引: ${index}`);
        return tabManager.hibernateTab(index);
      }
      logger.warn('TabHandler', LogCategory.IPC, `休眠标签页失败: 窗口不存在, ID: ${windowId}`);
      return false;
    } catch (error) {
      logger.error('TabHandler', LogCategory.IPC, `休眠标签页失败, 窗口ID: ${windowId}, 索引: ${index}:`, error);
      return false;
    }
  });

  logger.info('TabHandler', LogCategory.IPC, '标签页IPC处理程序设置完成');
}
